﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetroFramework.Forms;
using System.IO.Ports;
using System.IO;
using AForge.Video.DirectShow;

namespace PhotoCapturer
{
    public partial class FormSetting : MetroForm
    {
        private PhotoCameraOption _option = new PhotoCameraOption();
        public PhotoCameraOption Option
        {
            get { return _option; }
            set { _option = value; }
        }

        public FormSetting()
        {            
            InitializeComponent();
            LoadConfig();
        }

        private void LoadConfig()
        {
            if (!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            _option.Load();
        }

        private void InitCtrls()
        {
            metroComboBoxDevices.Items.Clear();
            int selectedIndex = 0;
            FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices.Count == 0)
            {
                MessageBox.Show("计算机未连接到任何图像设备.");
            }
            for (int i = 0; i < videoDevices.Count; i++)
            {
                string name = videoDevices[i].Name;
                metroComboBoxDevices.Items.Add(name);
                if (name.Equals(_option.CamName))
                {
                    selectedIndex = i;
                }
            }
            metroComboBoxDevices.SelectedIndex = selectedIndex;
            textBoxIndex.Text = selectedIndex.ToString();
            numericUpDownSharememorySize.Value = (int)(_option.ShareMemoryDataLength / 1048576);
        }

        private bool UpdateData()
        {
            if (metroComboBoxDevices.SelectedItem == null)
            {
                MessageBox.Show("没有选择镜头名称");
                return false;
            }
            _option.CamName = metroComboBoxDevices.SelectedItem.ToString();
            _option.CamIndex = metroComboBoxDevices.SelectedIndex;
            _option.ShareMemoryDataLength = (int)numericUpDownSharememorySize.Value * 1048576;
            return _option.Save();
        }

        private void buttonCancell_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (UpdateData())
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }

        private void FormSetting_Load(object sender, EventArgs e)
        {
            InitCtrls();
        }
    }
}
